package com.bee.health;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import juma.sdk.lite.JumaDevice;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bee.health.gl.GLImage;
import com.bee.health.gl.GLRender;
/***
 * 过程：1.开启扫描2.获取到设备以后，开启链接3.在获取数据处更新界面
 * @author bee
 *
 */
public class StepestimateActivity extends Activity {
	//保留小数点后两位
	DecimalFormat df = new DecimalFormat("#.##");
	private TextView tv_db,tv_btzq,tv_btdc,tv_arecount;

	private String title = "人体运动加速度曲线";
    private XYSeries seriesX,seriesY,seriesZ;//用来添加的数据集合
    private XYMultipleSeriesDataset mDataset;//数据集合
    private GraphicalView chart;//第三方的view
    private XYMultipleSeriesRenderer renderer;//渲染器
    private Context context;
    UUID myuuid = null;
    
	
	//private short bx = 0,by = 0,bz = 0;
	/*private float anglex = 0f;  null
	private float angley = 0f;  
	private float anglez = 0f; */
	
	private short bx = 0,by = 0,bz = 0,step=0,angley = 0;
	short k = 0 ;
	long ytrans = 0  , ytrans_base = 0;
	float ytrans_s = 0, ytrans_base_s = 0;

	short [] angle_y = new short [500];
	List<Float> list1 = new ArrayList<Float>(); 
	List<Float> list2 = new ArrayList<Float>(); 
	float rele;
	private float ave;
	
	GLRender render = new GLRender(this);  
    GLSurfaceView glView;//这个opengl
  
    int[] xv = new int[100];
    int[] yv = new int[100];
    
    private Message msg;
	private Handler handler;
	
	
	private JumaDevice device;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_stepestimate);
		 setTitle("Line Chart");
		 
		 tv_db = (TextView) findViewById(R.id.tv_db);
		tv_btzq = (TextView) findViewById(R.id.tv_btzq);
		tv_btdc = (TextView) findViewById(R.id.tv_btdc);
		tv_arecount = (TextView) findViewById(R.id.tv_arvcount);
		
		 
		 initDevice();
		 device.scan(null);//开始扫描,不然这样会报错
		 context = getApplicationContext();
	        GLImage.load(this.getResources());
	        glView = new GLSurfaceView(this);  
	        glView.setRenderer(render); 
	        LinearLayout layout1 = (LinearLayout)findViewById(R.id.ddd);
	        layout1.addView(glView);//OpenGL在用第一个
	        LinearLayout layout = (LinearLayout)findViewById(R.id.chat_layout);
	        mDataset = new XYMultipleSeriesDataset();//初始化和添加数据集
	        seriesX = new XYSeries("X");   
	        mDataset.addSeries(seriesX);   
	        seriesY = new XYSeries("Y");   
	        mDataset.addSeries(seriesY);   
	        seriesZ = new XYSeries("Z");   
	        mDataset.addSeries(seriesZ);   
	        
	        renderer = new XYMultipleSeriesRenderer();
	        renderer.addSeriesRenderer(setR(Color.RED,PointStyle.CIRCLE,true,3,true));
		    renderer.addSeriesRenderer(setR(Color.GREEN,PointStyle.CIRCLE,true,3,true));
		    renderer.addSeriesRenderer(setR(Color.YELLOW,PointStyle.CIRCLE,true,3,true));
	        setChartSettings(renderer, "X", "Y",0, 100, -1500, 1500, Color.WHITE, Color.WHITE);
	        chart = ChartFactory.getLineChartView(context, mDataset, renderer);
	        layout.addView(chart);//设置布局和填图
     
	        handler = new Handler(){
	        	//PS:先discover，再connect
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					
					switch (msg.what) {
					case 0://连接成功
						Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT).show();
						break;
					case 1://链接失败
	  					//Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
	  					device.scan(null);//开始扫描
	  					break;
						
					case 2://ERROR_CONNECT
						Toast.makeText(getApplicationContext(), "设备连接中...", Toast.LENGTH_SHORT).show();
					    device.connect(myuuid);//开启链接设备
						break;
					case 3://跟新数据
						updateChart();	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
						
						break;
					case 4:
						//Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
						break;
					case 5:
						Toast.makeText(getApplicationContext(), "获得数据", Toast.LENGTH_SHORT).show();
						break;
					default:
						break;
					}
				}

			
	        	
	        };
	}
	/**
	 * 获取平均值
	 * @param ave
	 * @return
	 */
	private int getBtCount(float ave) {
		int grade =0;
		for(int i =0;i<20;i++)
		{
			if((0.95-i*0.05)<=ave&&ave<=(1-i*0.05)){
				 grade = 95-i*5;
			}
		}
		return grade;
	}
	/**
     * 添加点，和数据集
     * @param series
     * @param y
     */
    private void addSeries(XYSeries series,int y){
        int length = series.getItemCount();
        if (length > 85) {
         length = 85;
        	  for (int i = 0; i+1 < length; i++) {
        		     xv[i] = (int) series.getX(i);
        		     yv[i] = (int) series.getY(i+1);
        		     }
        		     series.clear();
        		     for (int k = 0; k+1 < length; k++) {
        		         series.add(xv[k], yv[k]);
        		         }
        }
   
     series.add(length, y);
     mDataset.addSeries(series);
    }
    private void updateChart() {
    	
    	updateTx();
        mDataset.removeSeries(seriesX);
        mDataset.removeSeries(seriesY);
        mDataset.removeSeries(seriesZ);
        addSeries(seriesX,bx);
        addSeries(seriesY,by);
        addSeries(seriesZ,bz);	     
        chart.invalidate();
         }

		
	
	private void updateTx() {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				tv_db.setText(df.format(ave-0.05)+"");
				tv_btzq.setText(df.format(ave)+"");
				tv_btdc.setText(df.format((ave-0.05)/ave)+"");
				tv_arecount.setText(getBtCount(ave)+"");
				
			}
		});
		
	}
	/**
	 * 初始化装置
	 */
	 /**
     * 初始化蓝牙要链接的装置
     */
    private void initDevice(){
    	device = new JumaDevice(){

    		@Override
			public void onConnect(UUID arg0, int status) {
				if(status == JumaDevice.STATE_SUCCESS){
			
				msg = new Message();
				msg.what = 0;
				handler.sendMessage(msg);
				}else{
					
				}
			}

			@Override
			public void onDisconnect(UUID arg0, int status) {
				if(status == JumaDevice.STATE_SUCCESS){
					
				
					msg = new Message();
					msg.what = 1;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onDiscover(String name, UUID uuid, int rssi) {
				if("NigeL".equals(name)){
					System.out.println("uuid:"+uuid);
					myuuid=uuid;
					msg = new Message();
					msg.what = 2;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onError(Exception arg0, int arg1) {
				if(arg1 == JumaDevice.ERROR_SCAN){
					device.scan(null);
				}
				
			}

			@Override
			public void onMessage(byte type, byte[] arg1) {
				getSeries(arg1);
			}

			@Override
			public void onSend(int arg0) {
				
			}

			@Override
			public void onStopScan() {
				
			}

			@Override
			public void onUpdateFirmware(int arg0) {
				
			}
    		
    	};
    	device.init(getApplicationContext());
    }
    /***
     * 
     * @param arg1
     */
    public synchronized  void getSeries(byte[] arg1){ 
    	bx = 0;
		by = 0;
		bz = 0;
		bx |= arg1[0];
		bx <<= 8;
		bx |= (arg1[1]&0x00FF);
		by |= arg1[2];
		by <<= 8;
		by |= (arg1[3]&0x00FF);
		bz |= arg1[4];
		bz <<= 8;
		bz |= (arg1[5]&0x00FF);
		System.out.println("by:"+by);
	/*	angley = (bx*90)/1010;
		anglex = -(by*90)/1010;
		anglez = -(bz*90)/1010;*/
	/*	System.out.println("anglex:"+anglex);
		System.out.println("angley:"+angley);
		System.out.println("anglez:"+anglez);*/
		render.setXYZ(bx, by, bz);
		
		
		angley = by;
		
		int lengh = 500, i = 0, j = 0;

	/*	for(int a = 0;a<30;a++)
		{
			for(int h=0+a*10;h<10+a*10;h++)
			{
				angle_y[h] = (short) (h-a*10);
				
			}
		}*/
		angle_y[k] = angley;
		k ++;
		if(k >= 500)
		{
			for(j = 0; j < lengh; j ++)
			{
				for(i = 0; i < (lengh - j); i ++)
				{
					ytrans = (long) (angle_y[i] * angle_y[i + j] + ytrans);
				}
				ytrans_s =(float) (ytrans/(lengh - j));
			
				for(i = 0; i < lengh; i ++)
				{
					ytrans_base =(long) (angle_y[i] * angle_y[i] + ytrans_base);	
				}
				ytrans_base_s =(float) (ytrans_base/(lengh));
				rele = (float)(ytrans_s / ytrans_base_s);
			
				
				if(list1.size()<=10)
				{
					list1.add(rele);
					
				}else
				{
					
					//System.out.println(Collections.max(list1));//获取到了最大值
					list2.add(Collections.max(list1));
					//System.out.println(list2.size());
					if(list2.size()>50)
					{
						
						System.out.println(getAve(list2));
						ave = getAve(list2);
						
						
						
						list2.clear();
					}
					list1.clear();
				}
				ytrans = 0;
				ytrans_base = 0;
			}	

			k = 0;			
		}
	
		
		msg = new Message();
		msg.what = 3;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!得到数据以后才去跟新数据的
		handler.sendMessage(msg);
} 

    
	private float getAve(List<Float> list2) {
		//遍历这个集合，
		float sum = 0;
		for(int i=0;i<list2.size();i++)
		{
			sum+=list2.get(i);
		}
		return sum/(list2.size());
	}
    
    	protected XYSeriesRenderer setR(int color,PointStyle style, boolean FillPoints,int LineWidth,boolean ChartValues){
	    	 XYSeriesRenderer r = new XYSeriesRenderer();
		     
		     r.setColor(color);
		     r.setPointStyle(style);
		     r.setFillPoints(FillPoints);
		     r.setLineWidth(3);
		     r.setDisplayChartValues(true);
		     return r;
	    }
	    
	    protected void setChartSettings(XYMultipleSeriesRenderer renderer, String xTitle, String yTitle,
	    double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor) {
	     renderer.setChartTitle(title);
	     renderer.setXTitle(xTitle);
	     renderer.setYTitle(yTitle);
	     renderer.setAxisTitleTextSize(20);
	     renderer.setChartTitleTextSize(30);
	     renderer.setXAxisMin(xMin);
	     renderer.setXAxisMax(xMax);
	     renderer.setYAxisMin(yMin);
	     renderer.setYAxisMax(yMax);
	     renderer.setAxesColor(axesColor);
	     renderer.setLabelsColor(labelsColor);
	     renderer.setShowGrid(true);
	     renderer.setGridColor(Color.WHITE);
	     renderer.setXLabels(10);
	     renderer.setYLabels(10);
	     renderer.setXTitle("Point");
	     renderer.setYTitle("a");
	     renderer.setYLabelsAlign(Align.RIGHT);
	     renderer.setPointSize((float) 2);
	     renderer.setShowLegend(false);
	    }
	    
	    @Override
	    protected void onStop() {
	        super.onStop();
	      
	        if(device!=null)
	        {
	        	  device.disconnect(myuuid);
	        }
	      
	      
	     }
	    @Override
	    public void onDestroy() {
	     super.onDestroy();
	     if(device!=null)
	        {
	        	  device.disconnect(myuuid);
	        }
	    }

}
